package com.nxw.springcloud.admin.service.impl;

import com.nxw.springcloud.admin.config.UpdateTool;
import com.nxw.springcloud.admin.dto.GatewayRouteDefinition;
import com.nxw.springcloud.admin.entity.GatewayRoutes;
import com.nxw.springcloud.admin.respository.GatewayRoutesDao;
import com.nxw.springcloud.admin.service.inf.IRoutesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class RoutesServiceImpl implements IRoutesService {

    @Autowired private GatewayRoutesDao mapper;

    @Override
    public GatewayRoutes add(GatewayRoutes route) {
        route.setIsEbl(false);
        route.setIsDel(false);
        route.setCreateTime(new Date());
        route.setUpdateTime(new Date());
        return mapper.save(route);
    }

    @Override
    public GatewayRoutes update(GatewayRoutes route) {

        GatewayRoutes byPk = mapper.findById(route.getId()).orElse(null);
        UpdateTool.copyNullProperties(byPk, route);
        route.setUpdateTime(new Date());
        return mapper.save(route);
    }

    @Override
    public GatewayRoutes delete(Long id, boolean isDel) {

        GatewayRoutes one = mapper.getOne(id);
        one.setIsDel(isDel);
      return  mapper.saveAndFlush(one);
    }

    @Override
    public GatewayRoutes enableById(Long id, boolean isEbl) {
        GatewayRoutes one = mapper.getOne(id);
        one.setIsDel(isEbl);
        return  mapper.saveAndFlush(one);
    }

    @Override
    public GatewayRoutes getById(Long id) {
        return mapper.findById(id).get();
    }

    /**
     * 查询路由信息
     * @return
     */
    @Override
    public List<GatewayRoutes> getRoutes(GatewayRoutes route) {
        return mapper.findGatewayRoutesByIsDelAndIsEbl(route.getIsDel(),route.getIsEbl());
    }

    /**
     * 返回组装后网关需要的路由信息
     * @return
     */
    @Override
    public List<GatewayRouteDefinition> getRouteDefinitions() {
        List<GatewayRouteDefinition> routeDefinitions = new ArrayList<>();
        GatewayRoutes route = new GatewayRoutes();
        route.setIsDel(false);
        route.setIsEbl(false);
        List<GatewayRoutes> routes = getRoutes(route);
        for(GatewayRoutes gatewayRoute : routes){
            GatewayRouteDefinition routeDefinition = new GatewayRouteDefinition();
            routeDefinition.setId(gatewayRoute.getRouteId());
            routeDefinition.setUri(gatewayRoute.getRouteUri());
            routeDefinition.setFilters(gatewayRoute.getFilterDefinition());
            routeDefinition.setPredicates(gatewayRoute.getPredicateDefinition());
            routeDefinitions.add(routeDefinition);
        }
        return routeDefinitions;
    }
}
